// pages/message/message-dialog/message-dialog.js
import { dialogMessagesData, messageListData } from '../../../utils/mockData.js';

Page({
  data: {
    contactInfo: {},
    messageList: [],
    inputText: '',
    scrollIntoView: '',
    hasMore: false,
    // 独立的收/发消息数组，避免未定义报错
    receivedMessageList: [],
    sentMessageList: []
  },

  onLoad(options) {
    // 获取传递的联系人信息
    const { contactName } = options;
    
    if (!contactName) {
      wx.showToast({
        title: '参数错误',
        icon: 'none'
      });
      setTimeout(() => {
        wx.navigateBack();
      }, 1500);
      return;
    }
    
    // 加载对话数据
    this.loadDialogData(decodeURIComponent(contactName));
  },

  onShow() {
    // 页面显示时滚动到底部
    this.scrollToBottom();
  },

  // 加载对话数据
  loadDialogData(contactName) {
    
    // 从消息列表中找到对应的联系人信息
    const contact = messageListData.find(item => item.author.name === contactName);
    
    if (contact) {
      this.setData({
        contactInfo: {
          name: contact.author.name,
          avatar: contact.author.avatar,
          status: '在线'
        }
      });
      
      // 设置导航栏标题
      wx.setNavigationBarTitle({
        title: contact.author.name
      });
    } else {
      // 如果没有找到联系人，使用默认信息
      this.setData({
        contactInfo: {
          name: contactName,
          avatar: '/assets/images/default-avatar.jpg',
          status: '在线'
        }
      });
      
      wx.setNavigationBarTitle({
        title: contactName
      });
    }

    // 加载对话消息
    const messages = dialogMessagesData[contactName] || [];

    // 按类型切分出接收与发送列表
    const receivedMessageList = messages.filter(m => m.type === 'received');
    const sentMessageList = messages.filter(m => m.type === 'sent');

    this.setData({
      messageList: messages,
      receivedMessageList,
      sentMessageList,
      hasMore: messages.length > 10 // 模拟有更多消息
    });

    // 滚动到底部
    setTimeout(() => {
      this.scrollToBottom();
    }, 100);
  },

  // 滚动到底部
  scrollToBottom() {
    if (this.data.messageList.length > 0) {
      const lastMessage = this.data.messageList[this.data.messageList.length - 1];
      this.setData({
        scrollIntoView: `msg-${lastMessage.id}`
      });
    }
  },

  // 输入框内容变化
  onInputChange(e) {
    this.setData({
      inputText: e.detail.value
    });
  },

  // 发送消息
  onSendMessage() {
    const content = this.data.inputText.trim();
    if (!content) return;

    // 创建新消息
    const newMessage = {
      id: Date.now(),
      type: 'sent',
      content: content,
      time: this.getCurrentTime(),
      avatar: '/assets/images/my-avatar.jpg'
    };

    // 添加到消息列表
    const messageList = [...this.data.messageList, newMessage];
    const sentMessageList = [...this.data.sentMessageList, newMessage];
    this.setData({
      messageList,
      sentMessageList,
      inputText: '',
      scrollIntoView: `msg-${newMessage.id}`
    });

    // 模拟对方回复
    setTimeout(() => {
      this.simulateReply();
    }, 1000 + Math.random() * 2000);
  },

  // 模拟对方回复
  simulateReply() {
    const replies = [
      '好的，我明白了',
      '谢谢你的分享！',
      '这个建议很不错',
      '我会试试看的',
      '学到了，感谢！',
      '你说得对',
      '好的，没问题',
      '太棒了！'
    ];
    
    const randomReply = replies[Math.floor(Math.random() * replies.length)];
    
    const replyMessage = {
      id: Date.now() + 1,
      type: 'received',
      content: randomReply,
      time: this.getCurrentTime(),
      avatar: this.data.contactInfo.avatar
    };

    const messageList = [...this.data.messageList, replyMessage];
    const receivedMessageList = [...this.data.receivedMessageList, replyMessage];
    this.setData({
      messageList,
      receivedMessageList,
      scrollIntoView: `msg-${replyMessage.id}`
    });
  },

  // 获取当前时间
  getCurrentTime() {
    const now = new Date();
    const hours = now.getHours().toString().padStart(2, '0');
    const minutes = now.getMinutes().toString().padStart(2, '0');
    return `${hours}:${minutes}`;
  },

  // 语音输入
  onVoice() {
    wx.showToast({
      title: '语音功能开发中',
      icon: 'none'
    });
  },

  // 表情选择
  onEmoji() {
    wx.showToast({
      title: '表情功能开发中',
      icon: 'none'
    });
  },

  // 更多（+）入口
  onPlus() {
    wx.showActionSheet({
      itemList: ['照片/视频', '拍摄', '位置', '名片'],
      success: (res) => {
        wx.showToast({
          title: `选择了${res.tapIndex + 1}`,
          icon: 'none'
        });
      }
    });
  },

  // 更多操作
  onMore() {
    wx.showActionSheet({
      itemList: ['查看资料', '清空聊天记录', '举报'],
      success: (res) => {
        const actions = ['查看资料', '清空聊天记录', '举报'];
        wx.showToast({
          title: `选择了${actions[res.tapIndex]}`,
          icon: 'none'
        });
      }
    });
  },

  // 加载更多消息
  loadMoreMessages() {
    wx.showLoading({
      title: '加载中...'
    });

    setTimeout(() => {
      // 模拟加载更多消息
      const moreMessages = [
        {
          id: Date.now() - 1000,
          type: 'received',
          content: '这是更早的消息',
          time: '09:00',
          avatar: this.data.contactInfo.avatar
        }
      ];

      const messageList = [...moreMessages, ...this.data.messageList];
      const receivedMessageList = [
        ...moreMessages.filter(m => m.type === 'received'),
        ...this.data.receivedMessageList
      ];
      const sentMessageList = [
        ...moreMessages.filter(m => m.type === 'sent'),
        ...this.data.sentMessageList
      ];
      this.setData({
        messageList,
        receivedMessageList,
        sentMessageList,
        hasMore: false
      });

      wx.hideLoading();
      wx.showToast({
        title: '已加载全部消息',
        icon: 'none'
      });
    }, 1000);
  },

  // 分享给朋友
  onShareAppMessage() {
    return {
      title: `与${this.data.contactInfo.name}的对话`,
      path: `/pages/message/message-dialog/message-dialog?contactName=${this.data.contactInfo.name}`
    };
  }
})